package com.d3works.apps.cash.management.db.repo;

import com.d3works.apps.base.db.Company;
import com.d3works.apps.base.db.repo.SequenceRepository;
import com.d3works.apps.base.service.administration.SequenceService;
import com.d3works.apps.cash.management.db.Forecast;
import com.d3works.apps.cash.management.exception.CashManagementExceptionMessage;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import javax.persistence.PersistenceException;

public class CashManagementForecastRepository extends ForecastRepository {

  @Override
  public Forecast save(Forecast entity) {

    try {

      if (entity.getForecastSeq() == null) {
        Company company = entity.getCompany();

        String sequence =
            Beans.get(SequenceService.class)
                .getSequenceNumber(
                    SequenceRepository.FORECAST_SEQUENCE, company, Forecast.class, "forecastSeq");

        if (sequence == null) {
          throw new D3worksException(
              company,
              TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
              I18n.get(CashManagementExceptionMessage.FORECAST_SEQUENCE_ERROR),
              company.getName());

        } else {
          entity.setForecastSeq(sequence);
        }
      }
      return super.save(entity);
    } catch (Exception e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }
}
